const express = require('express')
const app = express()
const port = 8082
const sql = require("mssql");
const execSql = require("./methods/dosql")
const execFun = require("./methods/dofunc")

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', 'Authorization,X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method')
  res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PATCH, PUT, DELETE')
  res.header('Allow', 'GET, POST, PATCH, OPTIONS, PUT, DELETE')
  next();
});
app.get('/', (req, res) => {
  execSql("select * from stu",res)
})
app.get('/class', (req, res) => {
  execSql("select * from classes",res)
})
app.get('/major', (req, res) => {
  execSql("select * from majors",res)
})
app.get('/series', (req, res) => {
  execSql("select * from series",res)
})
app.get('/club', (req, res) => {
  execSql("select * from clubs",res)
})
app.get('/stuclub', (req, res) => {
  execSql("select * from stu_clubs",res)
})
app.get('/view', (req, res) => {
  execSql("select * from stu_club",res)
})

app.get('/query', (req, res) => {
  console.log(req.query)
  let q = req.query.userquery
  let sql = "select * from stu where stuname = " + "'"+q+"'"
  if(isNaN(parseInt(q))) execSql(sql,res)
  else if(!isNaN(parseInt(q))) execFun(res,"searchDigit","key",q)
})
//增
app.get('/add', (req, res) => {
  let q = req.query
  console.log(q.classno)
  let sql = "insert into stu (stuno,stuname,age,classno) values("+q.stuno+",'"+q.stuname+"',"+q.age+",'"+q.classno+"')"
  console.log(sql)
  execSql(sql,res)
})
//删
app.get('/delete', (req, res) => {
  let no = req.query.stuno
  let sql = "delete from stu where stuno = '" + no + "'"
  console.log(sql)
  execSql(sql,res)
})
//改
app.get('/update', (req, res) => {
  let stuno = req.query.stuno
  let stuname = req.query.stuname
  let age = req.query.age
  let classno = req.query.classno
  let sql = "update stu set stuname = '"+ stuname + "',"+"age = '"+ age + "',"+ "classno = '"+ classno + "'" + " where stuno = '" + stuno + "'"
  console.log(sql)
  execSql(sql,res)
})
//查
app.get('/updateclassno', (req, res) => {
  let oldclassno = req.query.oldclassno
  let newclassno = req.query.newclassno
  console.log(oldclassno,newclassno)
  execFun(res,"changeclassno","old","new",oldclassno,newclassno)
})
app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})